import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {View, Text} from '@tarojs/components';
import calendarObj from '../../../utils/calendar';
import {deepClone} from '../../../utils/tools';
import classnames from 'classnames';
import './components.scss';

export default class CalendarHotel extends Component {

  state = {
    initLoad: true,
    weeks: ["日", "一", "二", "三", "四", "五", "六"],
    todayDate: calendarObj.getCurrentDate(),
    realCurYear: calendarObj.getCurrentDate().split("-")[0],
    realCurMonth: calendarObj.getCurrentDate().split("-")[1],
    curYear: calendarObj.year,
    curMonth: calendarObj.month,
    month: [],
    stayDates: []
  }

  componentDidUpdate(preProps) {
    if (this.props.visible && this.state.month.length === 0) {
      this.setState(state => ({
        stayDates: state.stayDates.splice(0),
        initLoad: true,
      }), () => {
        this.getCalendar(this.props.calendarData);
      });
    }
    if (!this.props.visible) {
      this.state.stayDates.length < 2 &&
      this.prpos.currentDate.start &&
      this.prpos.currentDate.end &&
      this.resetStayDatesByCurrentDate();
    }
  }

  // 清空订退日期
  clearStayDates() {
    this.setState(state => ({
      stayDates: state.stayDates.splice(0)
    }));
  }

  // 初始化订退日期
  initStayDates() {
    const {month} = this.state;
    const {currentDate} = this.props;
    const stayDates = [currentDate.start];
    const startIdx = month.findIndex(dateObj => dateObj.date === currentDate.start); // 订日期在当月日历中的索引位
    const diffDay = calendarObj.getDateDiff(currentDate.start, currentDate.end);
    // 获取日期区间
    for (let i = 0; i < diffDay; i++) {
      const tempDate = month[startIdx + i + 1];
      stayDates.push(tempDate.date);
    }
    this.setState(state => ({
      stayDates: state.stayDates.concat(stayDates)
    }))
  }

  // 恢复订退日期
  resetStayDatesByCurrentDate() {
    const {month} = this.state;
    const {currentDate} = this.props;
    this.setState(state => ({
      stayDates: state.stayDates.splice(0)
    }), () => {
      const startIdx = month.findIndex(item => item.date === currentDate.start);
      const endIdx = month.findIndex(item => item.date === currentDate.end);
      const stayDates = deepClone(this.state.stayDates);
      // 包含起始日期
      for (let i = startIdx; i <= endIdx; i++) {
        stayDates.push(month[i].date);
        this.setState(state => ({
          stayDates: state.stayDates.concat(stayDates)
        }))
      }
      // console.log("恢复订退日期 - stayDates【后】 : ", this.stayDates);
    });
  }

  // 返回
  handleBack() {
    const tempDate = this.state.todayDate;
    calendarObj.loadCurrentMonthDate(tempDate);
    this.setState({
      curYear: calendarObj.year,
      curMonth: calendarObj.month
    }, () => {
      this.getCalendar(this.props.calendarData);
    })
  }

  // 切换月份
  handleChangeMonth(flag) {
    const {month, curMonth, stayDates} = this.state;

    const m = parseInt(curMonth);
    const d = stayDates.length > 0 ? stayDates[0].split("-")[2] : calendarObj.curMonthEveryDay[0];

    if (flag === "last") calendarObj.showLastMonth(m, d);
    else calendarObj.showNextMonth(m, d);

    this.setState({
      curYear: calendarObj.year,
      curMonth: calendarObj.month
    }, () => {
      this.getCalendar(this.props.calendarData);
    });
  }

  // 获取日历
  getCalendar(datas) {
    const {weeks} = this.state;
    this.setState(state => ({
      month: state.month.splice(0)
    }))
    Taro.showLoading({
      title: "加载中"
    })
    const newData = calendarObj.allDates.map(item => ({
      ...item,
      valid: false,
      group_id: null,
      price: 0,
      stock_balance: 0,
      surplus_stock: 0,
      label: "周" + weeks[new Date(item.date).getDay()],
    }));
    let nextStartIdx = 0; // 内循环的开始索引
    for (let i = 0, len = newData.length; i < len; i++) {
      for (let j = nextStartIdx, len2 = datas.length; j < len2; j++) {
        if (newData[i].date === datas[j].date) {
          nextStartIdx = j;
          newData[i] = Object.assign(
            {
              ...newData[i],
              ...datas[j],
              valid: datas[j].price > 0 && datas[j].surplus_stock > 0 && datas[j].stock_balance > 0
            }
          );
          break;
        }
      }
    }

    this.setState({month: newData, initLoad: false}, () => {
      this.state.stayDates.length === 0 && this.initStayDates();
      Taro.hideLoading();
    });
  }

  // 点击日期
  clickDate(item, idx) {
    if (!item.valid) return;
    if (item.stock_balance === 0) {
      Taro.showToast({
        title: "已约满",
        icon: "none"
      })
      return;
    }

    const {month, stayDates} = this.state;
    const {calendarData} = this.props;
    const itemDateIdx = calendarData.findIndex(dateObj => dateObj.date === item.date); // 日历库存中的索引位
    let temp_stayDates = deepClone(stayDates), status = true; // 订日期, 日期有效状态
    // 空日期 || 只有订日期
    if (temp_stayDates.length <= 1) {
      if (temp_stayDates.length === 0) temp_stayDates.push(item.date); // 订退被清空时

      const startIdx = month.findIndex(dateObj => dateObj.date === temp_stayDates[0]); // 订日期在当月日历中的索引位
      const diffDay = calendarObj.getDateDiff(temp_stayDates[0], item.date);
      // 获取日期区间
      for (let i = 0; i < diffDay; i++) {
        const tempDate = month[startIdx + i + 1];

        if (tempDate.valid && tempDate.stock_balance > 0) {
          temp_stayDates.push(tempDate.date);
        } else {
          status = false;
          break;
        }
      }
    } else {
      temp_stayDates.splice(0);
      // 重选
      temp_stayDates.push(item.date);

      const startIdx = month.findIndex(dateObj => dateObj.date === temp_stayDates[0]); // 订日期在当月日历中的索引位
      // 订日期是日历库存的最后一天 || 订日期的相邻日期无效 | 无库存
      if (itemDateIdx === calendarData.length - 1 || (!month[startIdx + 1].valid || month[startIdx + 1].stock_balance === 0)) {
        const endDate = calendarObj.getDateByDate(temp_stayDates[0], 1);
        temp_stayDates.push(endDate);
        this.setState({
          stayDates: deepClone(temp_stayDates)
        }, () => {
          this.closeCalendar();
          this.props.handleSureDate({date: this.state.stayDates});
        });
        return;
      }
    }

    if (!status) {
      Taro.showModal({
        content: "所选天数包含不可入住的日期，请重新选择",
        showCancel: false,
        confirmText: "知道了"
      });
      temp_stayDates.splice(0);
      this.setState(state => ({
        stayDates: state.stayDates.splice(0)
      }), () => {
        this.props.handleSureDate({date: []}); // 清空
      });
      return;
    }

    this.setState({
      stayDates: deepClone(temp_stayDates)
    }, () => {
      // 确定有效日期区间回传
      if (this.state.stayDates.length > 1) {
        this.props.handleSureDate({date: this.state.stayDates});
      }
    });
  }

  // 取消
  closeCalendar() {
    this.props.closeCalendar();
  }

  // 确定
  sureChoose() {
    this.props.handleSureDate({date: this.state.stayDates});
  }

  render() {
    const {
      visible,
      realCurYear,
      realCurMonth,
      curYear,
      curMonth,
      weeks,
      month,
      stayDates,
      initLoad
    } = this.state;

    return (
      <View className={classnames("calendar-page", {
        'cal-show': visible
      })}
      >
        {/* <View className="title-bar">
					<View className="wth left">
						<Text onClick={() => this.closeCalendar()}>取消</Text>
					</View>
					<View className="mid">选择日期</View>
					<View className="wth right">
						<Text onClick={() => this.sureChoose()}>确定</Text>
					</View>
				</View> */}

        <View className='mth-bar'>
          <View className='wth left'>
            <Text className='mth-btn' onClick={() => this.handleChangeMonth('last')}>上一月</Text>
          </View>
          <View className='mid'>
            {
              (realCurMonth != curMonth || realCurYear != curYear) &&
              <Text className='today' onClick={() => this.handleBack()}>今天</Text>
            }
            <Text>{curYear}年{curMonth}月</Text>
          </View>
          <View className='wth right'>
            <Text className='mth-btn' onClick={() => this.handleChangeMonth('next')}>下一月</Text>
          </View>
        </View>

        <View className='week-bar'>
          {
            weeks.map((item, index) => (
              <View key={index}>{item}</View>
            ))
          }
        </View>
        {
          month.length > 0 &&
          <View className='calendar-container'>
            {
              month.map((item, index) => (
                <View
                  key={index}
                  onClick={() => this.clickDate(item, index)}
                  className={classnames("calendar-block", {
                    ['stayActive']: stayDates.indexOf(item.date) > -1,
                    ['outStayActive']: stayDates.indexOf(item.date) > -1 && (!item.valid || !item.stock_balance || item.stock_balance === 0)
                  })}
                >
                  <View className='block-item'>
                    <View className='date'>
                      {/*!item.isCurMonth && <Text className="month">{item.month}月</Text>*/}
                      <Text className={classnames({
                        ['normal-date']: item.isCurrentMonth,
                        ['disabled-date']: !item.valid,
                        ['disabled-normal-date']: item.isCurrentMonth && !item.valid
                      })}
                      >{item.day}日</Text>
                    </View>
                    {
                      item.valid &&
                      <View className={classnames('date-info', {['date-info-disabled']: !item.isCurrentMonth})}>
                        <View>价:￥{item.price}</View>
                        <View>余: {item.surplus_stock}</View>
                        {
                          item.data.stock_balance && item.data.stock_balance > 0 && item.data.stock_balance <= 10 &&
                          <View className='red'>房源紧张</View>
                        }
                        {
                          !item.stock_balance && <View className='red'>已约满</View>
                        }
                      </View>
                    }
                  </View>
                  {
                    stayDates.length > 0 && stayDates[0] === item.date &&
                    <View className='reserve rs-in'>订</View>
                  }
                  {
                    stayDates.length > 1 && stayDates[stayDates.length - 1] === item.date &&
                    <View className='reserve rs-out'>退</View>
                  }
                </View>
              ))
            }
          </View>
        }
        {
          month.length === 0 && initLoad && <View className='empty-calendar'>加载中...</View>
        }
        {
          month.length === 0 && !initLoad && <View className='empty-calendar'>暂无可约日期</View>
        }
      </View>
    )
  }
}
